<template>
    <div id="login">
        <h1>研学管理平台登录</h1>
        <el-form label-width="100px" :model="data" id="form" :rules="rules" ref="ruleForm">
            <el-form-item prop="phone" label="请输入手机号" class="form-item">
                <el-input v-model="data.phone" maxlength="11"  placeholder="手机号"/>
            </el-form-item>
            <el-form-item prop="captcha" label="请输入验证码">
                <el-input class="form-item1" maxlength="4" placeholder="输入验证码" v-model="data.captcha">
                    <el-button @click.prevent="captcha" :disabled="disabled1" slot="append">
                        <span v-if="!disabled1">获取验证码</span>
                        <span v-if="disabled1">({{num1}})获取验证码</span>
                    </el-button>
                </el-input>
            </el-form-item>
            <el-form-item prop="password" label="请输入密码" class="form-item">
                <el-input type="password"  v-model="data.password" autocomplete="off" placeholder="6-16位密码，区分大小写"/>
            </el-form-item>
            <el-form-item label="请选择角色" class="form-item">
                <el-select v-model="data.identity" placeholder="请选择" :poper-append-to-body="false" id="select">
                    <el-option
                            v-for="item in data.identitys"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item calss="button">
                <el-button @click.prevent="login" class="button">
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {Form, FormItem, Input, Select, Option, Button} from "element-ui";
    import {post} from "@/request/AxiosMAX";

    import {UPDATE_ADMINUSER, UPDATE_BASE_USER, UPDATE_IDENTITY_AC} from "../../store/actions-types";

    export default {
        created() {
            let identity = localStorage.getItem("identity");
            identity = JSON.parse(identity);
            //更新到状态中
            this.$store.dispatch(UPDATE_IDENTITY_AC,identity);
            if (identity===1){
                let user = localStorage.getItem("user");
                user =  JSON.parse(user);
                //查询当前用户的最新消息
                if (user){
                    post("/api/Studies_to_travel/BaseRegister/queryByPrimaryKey",{id:user.id})
                        .then(res=>{
                            if (res.code === 0){
                                if (res.data.token===user.token){
                                    this.$store.dispatch(UPDATE_BASE_USER,user);
                                    this.$router.push("/base/home");
                                }else {
                                    return;
                                }
                            }
                        });
                }
            }else if (identity===2){
                let admin = localStorage.getItem("admin");
                admin =  JSON.parse(admin);
                if (admin){
                    post("/api/Studies_to_travel/admin/selectById",{id:admin.id})
                        .then(res=>{
                           if (res.code===0){
                               if (res.data.token===admin.token) {
                                   this.$store.dispatch(UPDATE_ADMINUSER, admin);
                                   this.$router.push("/admin");
                               }else {
                                   return;
                               }
                           }
                        });
                }else {
                    return;
                }
            }
        },
        name: "Login",
        components: {
            "el-form": Form,
            "el-form-item": FormItem,
            "el-input": Input,
            "el-select": Select,
            "el-option": Option,
            "el-button": Button
        },
        data() {

            let validatePhone = (rule, value, callback) =>{
                const $reg = /^1[3-9]\d{9}$/;
                if (value === ''){
                    callback(new Error('手机号不能为空'))
                }else if (!$reg.test(value)){
                    callback(new Error('手机号格式错误'))
                }
                else callback();

            };
            let validateVerificationCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('验证码不能为空'));
                }else if (!(value.length===4)){
                    callback(new Error('验证码长度小于4'));
                }
                else callback();
            };

            let validatePass = (rule, value, callback) => {
                const $regPass = /^[a-z0-9]{6,16}$/;
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else if (!$regPass.test(value)) {
                    setTimeout(() => callback(new Error('输入的密码不合法')), 100);
                }
            };
            return {
                user:{},
                disabled1: false,
                num1: 60,
                data: {
                    //后台验证码
                    verification: "",
                    //用户输入验证码
                    captcha: "",
                    //手机号
                    phone: '',
                    password: '',
                    identitys:
                        [{
                            value: 5,
                            label: '学校'
                        }, {
                            value: 4,
                            label: '教育厅'
                        }, {
                            value: 3,
                            label: '教育局'
                        }, {
                            value: 2,
                            label: '系统管理员'
                        }, {
                            value: 1,
                            label: "基地"
                        },
                        ],
                    identity: 1,
                },
                rules: {
                    captcha:[
                        {validator: validateVerificationCode, trigger: 'blur'}
                    ],
                    phone: [
                        {validator: validatePhone, trigger: 'blur'}
                    ],
                    password: [
                        {validator: validatePass, trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            //获取验证码
            captcha() {
                const $reg = /^1[3-9]\d{9}$/;
                if ($reg.test(this.data.phone)){
                    //定时器
                    let num = 60;
                    this.disabled1 = true;
                    let setInter = setInterval(() => {
                        this.num1 = --num;
                        if (this.num1 === 0) {
                            this.disabled1 = false;
                            clearInterval(setInter);
                        }
                    }, 1000)
                    post("/api/Studies_to_travel/BaseRegister/verification", {phone: this.data.phone})
                        .then(res => {
                            if (res.code === 0) {
                                //获取后台验证🐎
                                this.data.verification = res.data;
                            }
                        }).catch(err => {
                        console.info(err);
                    })
                }else {
                    this.$message({
                        message: '手机号格式错误',
                        type: 'error'
                    });
                }
            },
            login() {
                if (this.data.identity === 1) {
                    //判断验证码是否一致
                    if (this.data.verification === this.data.captcha) {
                        post("/api/Studies_to_travel/BaseRegister/login",
                            {phone: this.data.phone, pwd: this.data.password})
                            .then(res => {
                                if (res.code === 0) {
                                    //更新到vuex中的用户对象中
                                    localStorage.setItem("user", JSON.stringify(res.data));
                                    localStorage.setItem("identity",JSON.stringify(this.data.identity));
                                    //更新到vuex中
                                    this.$store.dispatch(UPDATE_BASE_USER, res.data);
                                    this.$store.dispatch(UPDATE_IDENTITY_AC,this.data.identity);
                                    this.$router.push("/base/home");
                                } else {
                                    this.$message({
                                        message: '手机号或密码错误',
                                        type: 'error'
                                    });
                                }
                            }).catch(err => {
                            console.info(err);
                            this.$message({
                                message: '网络错误',
                                type: 'error'
                            });
                        })
                    } else {
                        this.$message({
                            message: '验证码错误',
                            type: 'error'
                        });
                        console.info("登录失败")
                    }
                }else if (this.data.identity === 2){

                    //判断验证码是否一致
                    if (this.data.verification === this.data.captcha) {
                        post("/api/Studies_to_travel/admin/login",
                            {phone: this.data.phone, pwd: this.data.password})
                            .then(res => {
                                if (res.code === 0) {
                                    //更新到vuex中的用户对象中
                                    localStorage.setItem("admin", JSON.stringify(res.data));
                                    localStorage.setItem("identity",JSON.stringify(this.data.identity));
                                    //更新到vuex中
                                    this.$store.dispatch(UPDATE_ADMINUSER, res.data);
                                    this.$store.dispatch(UPDATE_IDENTITY_AC,this.data.identity);
                                    this.$router.push("/admin");
                                } else {
                                    this.$message({
                                        message: '手机号或密码错误',
                                        type: 'error'
                                    });
                                }
                            }).catch(err => {
                            console.info(err);
                            this.$message({
                                message: '网络错误',
                                type: 'error'
                            });
                        })
                    } else {
                        this.$message({
                            message: '验证码错误',
                            type: 'error'
                        });
                        console.info("登录失败")
                    }
                }
            }
        }
    }
</script>

<style scoped>
    #login {
        position: relative;
        width: 500px;
        height: 400px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, 50%);
    }

    #form {
        margin-left: -120px;
        margin-top: 30px;
    }

    /deep/ .form-item {
        width: 500px;
        margin-top: 10px;
        margin-bottom: 40px;
    }

    /deep/ #select {
        width: 400px !important;
    }

    /deep/ .button {
        width: 300px;
        margin-left: 20px;
    }

    .form-item1 {
        width: 400px;
    }

</style>
